import pandas as pd
import requests
import json
import os


def generate_json(dbname):
    url = 'http://127.0.0.1:5984/sitemap-data-%s/_all_docs/?include_docs=true' % dbname
    with open(dbname + '.json', 'wb') as f:
        f.write(requests.get(url).content)


def convert_json_to_csv(file, outfile=None):
    if outfile is None:
        head, _ = os.path.splitext(file)
        outfile = head + '.csv'
    dat = json.load(open(file, encoding='utf-8'))['rows']
    res = [d['doc'] for d in dat]
    pd.DataFrame(res).to_csv(outfile, encoding='utf-8', index=False, sep='\t',
                             columns=['weizhi', 'deals_riqi', 'deals_address',
                                      'deals_floor', 'deals_huxing',
                                      'deals_chengjiaojia', 'deals_mianji'])


def run(dbname):
    generate_json(dbname)
    convert_json_to_csv(dbname + '.json')


if __name__ == '__main__':
    run('fengxian')
